// 新增books

const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')
const { format } = require('../utils/getTime')
// 数据库地址
const uri = 'mongodb://localhost:27017/libraryDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 新增图书信息
const getBooksData = async (data) => {
  try {
    // 连接数据库
    await client.connect()

    // 获取数据库对象
    const db = client.db('libraryDB')

    // 获取图书表
    const booksDB = db.collection('books')
    // 新增数据
    const res = await booksDB.insertOne({
      ...data,
      created: format(),
      updated: format(),
    })
    if (res.acknowledged) {
      return {
        msg: '新增成功',
        time: format(),
        msgCode: 10000,
        data: {
          success: true,
        },
      }
    } else {
      return {
        msg: '新增失败',
        time: format(),
        msgCode: 99999,
        data: {
          success: false,
        },
      }
    }
  } catch (error) {
    console.log(error)
    return {
      msg: '服务器异常',
      success: false,
    }
  }
}

// 查询数据是否已存在
const queryBooksIseExist = async (isbn) => {
  try {
    await client.connect()
    const db = client.db('libraryDB')
    const booksDB = db.collection('books')
    const res = await booksDB.findOne(isbn)
    if (res) {
      return false
    }
    elseP
    return true
  } catch (error) {
    console.log(error, format())
  }
}

module.exports = { getBooksData }
